package cc.android.testapp.util;

import android.content.Context;
import android.os.Environment;
import android.widget.Toast;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;

import cc.android.testapp.ui.BoxNameDialog;
import cc.android.testapp.ui.MainActivity;
import cc.commons.util.CollUtil;
import cc.commons.util.FileUtil;

public class RenameYouhua {
    public static final String GongDanDir_REGX = "^\\d{6}-.*";
    public static final String WX_SCREESHOT_REGX = "Screenshot_.*_com\\.tencent\\.mm.*?\\.jpg";
    public static final String WX_EXPORT_REGX = "mmexport.*\\.jpg";
    public static final String YH_SCREESHOT_REGX = "Screenshot_.*io\\.dcloud\\.H5BAED6DD.*?\\.jpg";
    public static final String SYSTEM_CAMERA_REGX = "IMG_\\d*_\\d{6}(_\\d*)?\\.jpg";
    public static final String WATERMARKER_CAMERA_REGX = "IMG_\\d*_\\d{9}(_\\d*)?\\.jpg";

    public static void renameFuGua(Context pAct, File pDownloadDir) {
        File tDirMain = new File(pDownloadDir, "按需暂存/附挂/临时/");
        File[] tListP = tDirMain.listFiles((file) -> file.isDirectory() && file.getName().matches(GongDanDir_REGX));
        HashSet<String> tHandleP = new HashSet<>();
        if (CollUtil.isNotEmpty(tListP)) {
            for (File sP : tListP) {
                File[] tParts = sP.listFiles((file) -> file.isDirectory() && file.getName().matches("^\\d.*?"));
                ArrayList<File> tWMImgDir = new ArrayList<>();
                if (CollUtil.isNotEmpty(tParts)) tWMImgDir.addAll(Arrays.asList(tParts));
                tWMImgDir.add(sP);

                boolean tHandled = false;
                for (File sPart : tWMImgDir) {
                    File[] tImgs = sPart.listFiles((file) -> file.isFile() && file.getName().matches(WATERMARKER_CAMERA_REGX));
                    if (CollUtil.isNotEmpty(tImgs) && tImgs.length == 6) {
                        ArrayList<File> tImgFiles = new ArrayList<>(Arrays.asList(tImgs));
                        Collections.sort(tImgFiles);
                        String[] tNames = {"施工前3", "施工前2", "施工前1", "施工后3", "施工后2", "施工后1"};
                        for (int i = 0; i < 6; i++) {
                            File tTarget = tImgFiles.get(i);
                            tHandled |= rename(tTarget, tNames[i]);
                        }
                    }
                }

                File[] tImgs = sP.listFiles(file -> file.getName().endsWith(".jpg"));
                if (tImgs != null) for (File sFile : tImgs) {
                    String tName = sFile.getName();
                    if (tName.matches(YH_SCREESHOT_REGX)) {
                        tHandled |= rename(sFile, "隐患工单");
                    } else if (tName.matches(WX_SCREESHOT_REGX)) {
                        tHandled |= rename(sFile, "凭据");
                    } else if (tName.matches(WX_EXPORT_REGX)) {
                        tHandled |= rename(sFile, "派单照");
                    }
                }
                tImgs = sP.listFiles(file -> file.getName().matches(SYSTEM_CAMERA_REGX));
                if (CollUtil.isNotEmpty(tImgs)) {
                    tHandled |= rename(tImgs[0], "图纸");
                    if (tImgs.length > 1)
                        tHandled |= rename(tImgs[1], "派单照");
                }
                //TODO 233
                if (tHandled) tHandleP.add(sP.getName());
            }
        }
        notify(pAct, tHandleP);
    }

    public static void renameYHName(Context pAct, File pDownloadDir) {
        File tDirMain = new File(pDownloadDir, "按需暂存/优化整治/临时/");
        File[] tListP = tDirMain.listFiles((file) -> file.isDirectory() && file.getName().matches(GongDanDir_REGX));
        HashSet<String> tHandleP = new HashSet<>();
        if (CollUtil.isNotEmpty(tListP)) {
            for (File sP : tListP) {
                File[] tParts = sP.listFiles((file) -> file.isDirectory() && file.getName().matches("^\\d.*?"));
                boolean tHandled = false;
                if (CollUtil.isNotEmpty(tParts)) {
                    for (File sPart : tParts) {
                        File[] tImgs = sPart.listFiles((file) -> file.isFile() && file.getName().matches(WATERMARKER_CAMERA_REGX));
                        if (CollUtil.isNotEmpty(tImgs) && tImgs.length == 5) {
                            ArrayList<File> tImgFiles = new ArrayList<>(Arrays.asList(tImgs));
                            Collections.sort(tImgFiles);
                            String tPName = sPart.getName();
                            String[] tNames = {"施工前%s-2", "施工前%s-1", "施工中%s", "施工后%s-2", "施工后%s-1"};
                            for (int i = 0; i < 5; i++) {
                                File tTarget = tImgFiles.get(i);
                                String tTName = String.format(tNames[i], tPName) + ".jpg";
                                File tDest = new File(sPart.getParent(), tNames[i].substring(0, 3) + File.separator + tTName);
                                if (tDest.getParentFile().isDirectory() || tDest.getParentFile().mkdirs()) {
                                    tHandled |= tTarget.renameTo(tDest);
                                }
                            }
                            FileUtil.deleteFile(sPart);
                        }
                    }
                }
                if (tHandled) tHandleP.add(sP.getName());
            }
        }

        notify(pAct, tHandleP);
    }



    public static boolean tryShow(MainActivity pAct) {
        HashMap<File, String> tImgs = new HashMap<>();
        //1
        File[] tDirImgs = getTimeHeadFile("DCIM/Camera/",
                SYSTEM_CAMERA_REGX, 1);
        if (CollUtil.isEmpty(tDirImgs)) {
            Toast.makeText(pAct, "无派单照", Toast.LENGTH_SHORT).show();
            return false;
        }
        tImgs.put(tDirImgs[0], "派单照.jpg");
        // 2
        tDirImgs = getTimeHeadFile("DCIM/Screenshots/",
                YH_SCREESHOT_REGX, 1);
        if (CollUtil.isEmpty(tDirImgs)) {
            Toast.makeText(pAct, "未截图隐患工单", Toast.LENGTH_SHORT).show();
            return false;
        }
        tImgs.put(tDirImgs[0], "隐患工单.jpg");
        //3
        tDirImgs = getTimeHeadFile("DCIM/WaterMaker/",
                WATERMARKER_CAMERA_REGX, 6);
        if (CollUtil.isEmpty(tDirImgs)) {
            Toast.makeText(pAct, "水印照片数量不足", Toast.LENGTH_SHORT).show();
            return false;
        }
        int tIndex = 0;
        for (String sPrefix : new String[]{"施工后%d.jpg", "施工前%d.jpg"}) {
            for (int i = 1; i <= 3; i++, tIndex++) {
                tImgs.put(tDirImgs[tIndex], String.format(sPrefix, i));
            }
        }
        //4
        new BoxNameDialog(pAct, tImgs).show();
        return true;
    }

    public static void notify(Context pAct, Collection<String> pHandle) {
        if (pHandle.isEmpty()) {
            Toast.makeText(pAct, "无文件可处理", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(pAct, "处理了: " + pHandle, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 重命名图片文件名字
     *
     * @param pTarget 目标图片
     * @param pName   新的文件名字,不包含后缀
     * @return 是否重命名成功
     */
    public static boolean rename(File pTarget, String pName) {
        return pTarget.renameTo(new File(pTarget.getParent(), pName + ".jpg"));
    }

    public static File[] getTimeHeadFile(String pDir, String pImgFilter, int pAmount) {
        File tDir = new File(Environment.getExternalStorageDirectory(), pDir);
        File[] tDirImgs = tDir.listFiles(File::isFile);
        if (CollUtil.isEmpty(tDirImgs) || tDirImgs.length < pAmount) return null;

        Arrays.sort(tDirImgs, (file1, file2) -> {
            long tV = file1.lastModified() - file2.lastModified();
            return tV == 0 ? 0 : (tV > 0 ? -1 : 1);
        });
        for (int i = 0; i < pAmount; i++) {
            if (!tDirImgs[i].getName().matches(pImgFilter)) return null;
        }
        return tDirImgs;
    }
}
